//
//  ZZMusicListController.m
//  ZZBlue
//
//  Created by stonesMonkey on 2017/9/16.
//  Copyright © 2017年 stonesMonkey. All rights reserved.
//

#import "ZZMusicListController.h"
#import "ZZMusicAddMusicCell.h"
#import "ZZMusicList.h"
#import "ZZMusicModel.h"
#import "ZZMusicListGroup.h"
#import "ZZMusicCell.h"
#import "ZZMusicGroupCell.h"
#import "MusicTool.h"
#import "ZZMusicList.h"
#import "ZZMusicListGroup.h"
#import <MediaPlayer/MediaPlayer.h>
#import "ZZHudViewController.h"

#define musicListPath @"musicList.plist"
#define kListModelKey @"listModelKey"
#define kMusicCellIndetifier @"musicCellIndetifier"

@interface ZZMusicListController ()<MPMediaPickerControllerDelegate>

@property (nonatomic, strong)ZZMusicListGroup *listModels;
@property (nonatomic,strong) MPMediaPickerController *mediaPicker;//媒体选择控制器
@property (nonatomic,strong) MPMusicPlayerController *musicPlayer; //音乐播放器

@property (nonatomic, strong)NSIndexPath *playerIndexPath;



@end

@implementation ZZMusicListController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = NSLocalizedString(@"MUSIC_MuscicList_PlayList", nil);
    titleLabel.font = [UIFont systemFontOfSize:17];
    titleLabel.textColor = [UIColor whiteColor];
    [titleLabel sizeToFit];
    self.navigationItem.titleView = titleLabel;
    
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"icon_fanh"] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(0, 0, 16, 16);
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchDown];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [rightBtn setTitle:NSLocalizedString(@"MUSIC_MuscicList_AddSection", nil) forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.6] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnDidClick) forControlEvents:UIControlEventTouchDown];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    rightBtn.frame = CGRectMake(0, 0, 60, 30);
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    ZZMusicAddMusicCell *musicCell = [ZZMusicAddMusicCell xibInstance];
    musicCell.didClick = ^ {
        
        [self presentMedialVc];
    };
    musicCell.frame = CGRectMake(0, 0, Z_SCREEN_WIDTH, 54 * Z_Scale);
    
    self.tableView.tableHeaderView = musicCell;
    
    UINib *nib = [UINib nibWithNibName:@"ZZMusicCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kMusicCellIndetifier];
    self.tableView.rowHeight = 54;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.backgroundColor = SEPARATOR_BG_COLOR_Low;;
}


#pragma mark - Func

- (void)presentMedialVc {
    
    MPMediaPickerController *vc = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
    vc.delegate = self;
//    self.musicPlayer = vc;
    vc.allowsPickingMultipleItems = YES;
    [self presentViewController:vc animated:YES completion:nil];
    
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter
     addObserver: self
     selector:    @selector (handle_NowPlayingItemChanged:)
     name:        MPMusicPlayerControllerNowPlayingItemDidChangeNotification
     object:      self.musicPlayer];
    
    [notificationCenter
     addObserver: self
     selector:    @selector (handle_PlaybackStateChanged:)
     name:        MPMusicPlayerControllerPlaybackStateDidChangeNotification
     object:      self.musicPlayer];
    
//    [self.musicPlayer beginGeneratingPlaybackNotifications];
}

- (void)handle_NowPlayingItemChanged:(id)Id {
    
    
}

- (void)handle_PlaybackStateChanged:(id)obj {
    
    
}

- (void)changeMusicModel:(ZZMusicModel *)model musicList:(ZZMusicList *)musicList {
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive
                                                         handler:^(UIAlertAction * action) {}];
    
    UIAlertAction* moveAction = [UIAlertAction actionWithTitle:@"移动到播放列表" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        
        [alert dismissViewControllerAnimated:YES completion:nil];
        
//        ZZHudViewController *hudVc = [ZZHudViewController new];
//        hudVc.view.backgroundColor;
        ZZHudView *hudView = [ZZHudView xibInstance];
        hudView.listGroup = [MusicTool new].listModels;
        
        hudView.frame = Z_SCREEN;
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:hudView];
        hudView.musicModel = model;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(popView:)];
        hudView.gestureRecognizers = @[tap];
        hudView.userInteractionEnabled = YES;
        hudView.listMusic = musicList;
        hudView.moveCommit = ^ {
          
            [self.tableView reloadData];
        };
        
    }];
    
    UIAlertAction* deleteAction = [UIAlertAction actionWithTitle:@"删除歌曲" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
       
        
        [[MusicTool new] removeMusic:model musicList:musicList];
        [self.tableView reloadData];
    }];
    
    
    
    [alert addAction:moveAction];
    [alert addAction:deleteAction];
    [alert addAction:cancleAction];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

- (void)popView:(UITapGestureRecognizer *)tap {
    
    [tap.view removeFromSuperview];
}

- (void)back {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightBtnDidClick {
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"新建分组"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    
    __weak __block UITextField * weakTextFiled = nil;
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
       
        textField.placeholder = @"请输入组名称";
        weakTextFiled = textField;
    }];
    
//    alert.view.backgroundColor = [UIColor blackColor];
    
    UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive
                                                         handler:^(UIAlertAction * action) {}];
    
    UIAlertAction* sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                                                           
        
        NSString *seactionStr =  weakTextFiled.text;
        [[MusicTool new] addSeaction:seactionStr];
        // 刷新
        [self reloadDate];
        
    }];
    
    
    [alert addAction:cancleAction];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)reloadDate {
    
    [self.tableView reloadData];
}

- (void)tableViewSectionDidSelect:(UITapGestureRecognizer *)tap {
    
    ZZMusicGroupCell *cell = (ZZMusicGroupCell *)tap.view;
    ZZMusicList *list = cell.listModel;
    list.isShow = !list.isShow;
    [self.tableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.listModels.listgroup.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    ZZMusicList *list = self.listModels.listgroup[section];
    if (list.isShow == NO) {
        
        return 0;
    }
    
    return list.musicList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZZMusicCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kMusicCellIndetifier];
    ZZMusicList *list = self.listModels.listgroup[indexPath.section];
    
    ZZMusicModel *model = list.musicList[indexPath.row];
  
    cell.model = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.musicSelectBlock = ^(ZZMusicModel *model, ZZMusicList *musicList){
        
        [self changeMusicModel:model musicList:musicList];
    };
    cell.musicList = list;
    
    return cell;
}

// 设置头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    ZZMusicGroupCell *groupCell = [ZZMusicGroupCell xibInstance];
    ZZMusicList *list = self.listModels.listgroup[section];
    groupCell.listModel = list;
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableViewSectionDidSelect:)];
    groupCell.userInteractionEnabled = YES;
    groupCell.gestureRecognizers = @[tap];
    
    return groupCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    ZZMusicList *list = self.listModels.listgroup[indexPath.section];
    
    ZZMusicModel *model = list.musicList[indexPath.row];
    self.playerModel = model;
    if (model.isPlayer) {
        
        model.isPlayer = NO;
        if (self.pasuseMusic) {
            
            self.pasuseMusic(model, list);
            
        }
        [self.tableView reloadData];
        return;
    }
    
    // 让其他Model都为NO;
    ZZMusicListGroup *group = [[MusicTool new] listModels];
    for (ZZMusicList *list in group.listgroup) {
        
        for (ZZMusicModel *model in list.musicList) {
            
            model.isPlayer = NO;
        }
    }
    
    model.isPlayer = YES;
    // 点击播放音乐
    if (self.playerMusic) {
        
        self.playerMusic(model,list);
    }
    
    self.playerIndexPath = indexPath;
    
  
    
    [self.tableView reloadData];
   
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    ZZMusicList *list = self.listModels.listgroup[section];
    if ([list.listName isEqualToString:NSLocalizedString(@"MUSIC_MuscicList_NotGroup", nil)] && list.musicList.count == 0) {
        
        return 0;
    }
    
    return 54;
}


#pragma mark - 通知
/**
 *  添加通知
 */
-(void)addNotification{
    NSNotificationCenter *notificationCenter=[NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(playbackStateChange:) name:MPMusicPlayerControllerPlaybackStateDidChangeNotification object:self.musicPlayer];
}

/**
 *  播放状态改变通知
 *
 *  @param notification 通知对象
 */
-(void)playbackStateChange:(NSNotification *)notification{
    switch (self.musicPlayer.playbackState) {
        case MPMusicPlaybackStatePlaying:
            NSLog(@"正在播放...");
            break;
        case MPMusicPlaybackStatePaused:
            NSLog(@"播放暂停.");
            break;
        case MPMusicPlaybackStateStopped:
            NSLog(@"播放停止.");
            break;
        default:
            break;
    }
}


#pragma mark - MPMediaPickerControllerDelegate
//选择完成
-(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection{
    
    
    for (MPMediaItem *mediaItem in mediaItemCollection.items) {
        
        [self resolverMediaItem:mediaItem];
    }
    
    [[MusicTool new] save];
    [self.tableView reloadData];
}

- (void)resolverMediaItem:(MPMediaItem *)song
{
    //歌曲路径
    NSURL *url = [song valueForProperty: MPMediaItemPropertyAssetURL];
    
    if (url == nil) {
        
        [MBProgressHUD zAlertError:@"版权原因导入失败"];
        return;
    }
    //歌名
    NSString *name = [song valueForProperty: MPMediaItemPropertyTitle];
    ZZMusicListGroup *group = [[MusicTool new] listModels];
    for (ZZMusicList *list in group.listgroup) {
        
        for (ZZMusicModel *model in list.musicList) {
            
            if ([model.musicName isEqualToString:name]) {
                
                [MBProgressHUD zAlertError:@"已存在这首歌曲"];
                return;
            }
        }
    }
  
    //歌手名字
    NSString *songer = [song valueForProperty: MPMediaItemPropertyArtist];
    //歌曲时长（单位：秒）
    NSTimeInterval INW = [[song valueForProperty: MPMediaItemPropertyPlaybackDuration] doubleValue];
    NSString *time;
    if((int)INW%60<10)
    {
        time = [NSString stringWithFormat:@"%d:0%d",(int)INW/60,(int)INW%60];
    }
    else
    {
        time = [NSString stringWithFormat:@"%d:%d",(int)INW/60,(int)INW%60];
    }
    if(songer == nil)
    {
        songer = nil;
    }
    //歌曲插图（如果没有插图，则返回nil）
//    MPMediaItemArtwork *artwork = [song valueForProperty: MPMediaItemPropertyArtwork];
    //从插图中获取图像，参数size是图像的大小
    // 这里可以做图片保存
//    UIImage *image = [artwork imageWithSize:CGSizeMake(300, 300)];
//    NSData
    ZZMusicModel *model = [ZZMusicModel new];
    model.auther = songer;
    model.path = url;
    model.musicName = name;
    model.duration = INW;
    
    ZZMusicList *defalutList = nil;
    for(ZZMusicList *list in  [MusicTool new].listModels.listgroup) {
        
        if ([list.signName isEqualToString:NSLocalizedString(@"MUSIC_MuscicList_NotGroup", nil)]) {
            
            defalutList = list;
            [list.musicList addObject:model];
        }
    }
    
    
    
    
    //    self.label.text = [NSString stringWithFormat:@"歌名：%@ \n 歌曲路径：%@ \n 歌手名字:%@ \n 歌曲时长%@ \n 歌曲插图：%@",name,url,songer,time,image];
}
//取消选择
-(void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - set & get
- (ZZMusicListGroup *)listModels {
    
    if (_listModels == nil) {
        
        MusicTool *tool = [MusicTool new];
        _listModels = tool.listModels;
    }
    
    return _listModels;
}

/**
 *  获得音乐播放器
 *
 *  @return 音乐播放器
 */
-(MPMusicPlayerController *)musicPlayer{
    if (!_musicPlayer) {
        _musicPlayer=[MPMusicPlayerController systemMusicPlayer];
//        [_musicPlayer beginGeneratingPlaybackNotifications];//开启通知，否则监控不到MPMusicPlayerController的通知
        [self addNotification];//添加通知
        //如果不使用MPMediaPickerController可以使用如下方法获得音乐库媒体队列
        //[_musicPlayer setQueueWithItemCollection:[self getLocalMediaItemCollection]];
    }
    return _musicPlayer;
}

/**
 *  创建媒体选择器
 *
 *  @return 媒体选择器
 */
-(MPMediaPickerController *)mediaPicker{
    if (!_mediaPicker) {
        //初始化媒体选择器，这里设置媒体类型为音乐，其实这里也可以选择视频、广播等
        //        _mediaPicker=[[MPMediaPickerController alloc]initWithMediaTypes:MPMediaTypeMusic];
        _mediaPicker=[[MPMediaPickerController alloc]initWithMediaTypes:MPMediaTypeAny];
        _mediaPicker.allowsPickingMultipleItems=YES;//允许多选
        //        _mediaPicker.showsCloudItems=YES;//显示icloud选项
        _mediaPicker.prompt=@"请选择要播放的音乐";
        _mediaPicker.delegate=self;//设置选择器代理
    }
    return _mediaPicker;
}


@end
